package com.vois.jack.btmgr.classicbase;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.util.Log;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@SuppressLint("MissingPermission")
public class BtDeviceBuilder {
    static private Map<String, BtDeviceInfo> btNameDeviceMap = new HashMap<>();
    static class BtDeviceInfo {
        Class < ? extends BtDevice> btDevClass;
        int burstType;

        public BtDeviceInfo(Class<? extends BtDevice> btDevClass, int burstType) {
            this.btDevClass = btDevClass;
            this.burstType = burstType;
        }
    }

    static public void registerBtDeviceClass(String name, Class<? extends BtDevice> btDevClass, int burstType) {
        if (!btNameDeviceMap.containsKey(name)) {
            btNameDeviceMap.put(name, new BtDeviceInfo(btDevClass, burstType));
        }
    }

    static public void unregisterBtDeviceClass(String name) {
        btNameDeviceMap.remove(name);
    }

    static public int getBtDeviceSrcType(BluetoothDevice device) {
        Set<String> keys = btNameDeviceMap.keySet();
        String deviceName = device.getName();
        if (deviceName != null) {
            for (String key : keys) {
                Pattern pattern = Pattern.compile(key);
                Matcher matcher = pattern.matcher(deviceName);

                if (matcher.find()) {
                    return btNameDeviceMap.get(key).burstType;
                }
            }
        }

        return 1;
    }

    static public BtDevice buildBtDevice(BluetoothDevice device) {
        Set<String> keys = btNameDeviceMap.keySet();
        Class<? extends BtDevice> cls = null;
        BtDevice btDevice = null;

        String keyName = null;
        String deviceName = device.getName();
        if (deviceName != null) {
            for (String key : keys) {
                Pattern pattern = Pattern.compile(key);
                Matcher matcher = pattern.matcher(deviceName);

                Log.d("buildBtDevice", "buildBtDevice: " + key);

                if (matcher.find()) {
                    keyName = key;
                    break;
                }
            }
        }

        if (keyName != null) {
            cls = btNameDeviceMap.get(keyName).btDevClass;
        }

        Log.d("buildBtDevice", "buildBtDevice: " + keyName + ":" + ((cls != null) ? cls.getName() : "invalid"));

        if (cls == null) {
            cls = DefaultBtDevice.class;
        }

        try {
            btDevice = cls.newInstance();
            btDevice.init(device);
        }catch (IllegalAccessException | InstantiationException e) {
            e.printStackTrace();
        }

        return btDevice;
    }

}
